package com.yunhe.mybatis.service.impl;

import com.yunhe.mybatis.common.utils.SqlSessionManager;
import com.yunhe.mybatis.dao.user.UserDao;
import com.yunhe.mybatis.dto.Pageable;
import com.yunhe.mybatis.entity.User;
import com.yunhe.mybatis.service.UserService;

import java.util.List;

public class UserServiceImpl implements UserService {

    @Override
    public void save(User user) {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        userDao.save(user);
    }

    @Override
    public void remove(Integer id) {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        userDao.remove(id);
    }

    @Override
    public void removebatch(Integer[] ids) {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        userDao.removebatch(ids);
    }

    @Override
    public void update(User user) {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        userDao.update(user);
    }

    @Override
    public User find(Integer id) {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        return userDao.find(id);
    }

    @Override
    public void findByName(String name) {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        userDao.findByName(name);
    }

    @Override
    public List<User> findAll() {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        return userDao.findAll();
    }

    @Override
    public Pageable findForPage(int page, int size, String name, String className, Integer sex) {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        Pageable pageable = new Pageable();
        pageable.setCurrent(page);
        pageable.setSize(size);
        int count = userDao.count();
        pageable.setCount(count);
        if(count > 0 ){
            name = name != null ? "%" + name +"%" : name;
            List<User> list = userDao.findList((page - 1) * size, size,  name,className,sex);
            pageable.setRows(list);

            int pageCount = count/size;
            pageCount = count % size == 0 ? pageCount : pageCount + 1;
            pageable.setPageCount(pageCount);
        }
        return pageable;
    }

    @Override
    public User findper(Integer id) {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        return userDao.findper(id);
    }

    @Override
    public void updateper(User user) {
        UserDao userDao = SqlSessionManager.getSqlSession().getMapper(UserDao.class);
        userDao.updateper(user);
    }


}
